package com.haian.slidealbum.control;

import java.io.File;
import java.util.ArrayList;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Contacts;
import android.widget.RemoteViews;

import com.haian.slidealbum.R;
import com.haian.slidealbum.common.UtilsCommon;
import com.haian.slidealbum.model.helper.DBHandler;
import com.haian.slidealbum.model.object.ObjectImage;

@SuppressWarnings("deprecation")
public class WidgetUpdateService extends Service {

	static ArrayList<ObjectImage> arrayItem;
	static int positionCurrent;
	static int idAlbumCueent;
	static int timeInterval;
	Context mContext;
	int appWidgetId;
	public static boolean statusCurrentAlbum, updateInterval;

	@Override
	public void onStart(final Intent intent, int startId) {
		super.onStart(intent, startId);

		try {
			statusCurrentAlbum = false;
			arrayItem = new ArrayList<ObjectImage>();
			mContext = this;
			positionCurrent = -1;
			idAlbumCueent = 0;
			timeInterval = DBHandler.getInterval(mContext);
			updateInterval = false;
			appWidgetId = -1;
			try {
				appWidgetId = intent.getIntExtra("appWidgetId",
						AppWidgetManager.INVALID_APPWIDGET_ID);
			} catch (Exception e) {
				// TODO: handle exception
			}
			

			final Runnable runnable = new Runnable() {
				@Override
				public void run() {
//					while (0 < 1) {
						if (appWidgetId != -1) {
							RemoteViews update = buildUpdate(
									WidgetUpdateService.this, appWidgetId);
							AppWidgetManager manager = AppWidgetManager
									.getInstance(WidgetUpdateService.this);
							manager.updateAppWidget(appWidgetId, update);
						}
//					}
				}
			};
			
			final Handler handler = new Handler();
			
			Thread thread = new Thread()
			{
			    @Override
			    public void run() {
			    	while (0 < 1) {
			    		try {
							sleep((timeInterval + 1) * 1000);
							handler.postDelayed(runnable, (timeInterval + 1) * 1000);
//						    Log.d("Luong", "Luong_________________________ Have been run sleep: "+timeInterval);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
			    		
			    	}
			    }
			};

			thread.start();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static RemoteViews buildUpdate(Context context, int appWidgetId) {
		RemoteViews view = new RemoteViews(context.getPackageName(),
				R.layout.widget_screen);
		try {
			if(updateInterval)
			{
				updateInterval = false;
				timeInterval = DBHandler.getInterval(context);
			}
			String path = "";
			Cursor cursorAlbum = DBHandler.getAlbumCurrent(context);
			if (cursorAlbum.moveToFirst()) {
				int albumid = cursorAlbum.getInt(0);
				if (albumid != idAlbumCueent || statusCurrentAlbum) {
					idAlbumCueent = albumid;
					positionCurrent = -1;
					statusCurrentAlbum = false;
					Cursor cursorItem = DBHandler.getItemByAlbumId(context, String.valueOf(albumid));
					if (cursorItem.moveToFirst()) {
						ArrayList<ObjectImage> arrayItemTemp = new ArrayList<ObjectImage>();
						do {
							ObjectImage mObjectItem = new ObjectImage();
							mObjectItem.setIdImage(cursorItem.getInt(0));
							mObjectItem.setUrlImage(cursorItem.getString(1));
							arrayItemTemp.add(mObjectItem);
						} while (cursorItem.moveToNext());
						if(arrayItemTemp.size() >0)
						{
							arrayItem.clear();
							arrayItem.addAll(arrayItemTemp);
						}
					}
				}
			}
			DBHandler.closeDB(context);
			if (positionCurrent >= -1 && positionCurrent < arrayItem.size() - 1) {
				positionCurrent++;
			} else {
				positionCurrent = 0;
			}
			path = arrayItem.get(positionCurrent).getUrlImage();
			if(path.equals("")== false)
			{
				File f = new File(path);
				view.setImageViewBitmap(R.id.imgView, UtilsCommon.reSizeFile(f));
//				Log.d("Luong", "Luong________ Have been view img: "+path);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		// click
		try {
			Intent configIntent = new Intent(context, AlbumManageActivity.class);
			Uri data = ContentUris.withAppendedId(Contacts.People.CONTENT_URI,(int) appWidgetId);
			configIntent.setData(data);
			PendingIntent pending = PendingIntent.getActivity(context, 0,
					configIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			view.setOnClickPendingIntent(R.id.btnSetting, pending);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return view;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}
